<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/2/25 0025
 * Time: 下午 1:34
 */
namespace app\common\service;

use app\common\BaseHelper;
use think\Cache;
use think\Controller;

class Utils extends Controller{

    /**
     * 获取微信AccessToken
     * @return bool
     */
    public static function getAccessToken(){
        //先从缓存里面读取token，看有没有过期
        $token = Cache::get('MiaojiehuiAccessToken');
        if(!empty($token)){
            $token = json_decode($token, true);
            if(!empty($token['expires_time']) && !empty($token['access_token']) && time()<$token['expires_time']){
                return $token['access_token'];
            }
        }
        $appid = config('wx.app_id');
        $secret = config('wx.app_secret');
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
        $result = json_decode(BaseHelper::curlGet($url),true);
        if (empty($result['access_token'])) {
            return false;
        }
        //令牌
        $data['access_token'] = $result['access_token'];
        //过期时间(1小时50分钟)
        $data['expires_time'] = time() + 60 * 60 + 50 * 60;
        Cache::set('MiaojiehuiAccessToken',json_encode($data),$data['expires_time']);
        return $data['access_token'];
    }

    /**
     * 记录日志
     * @param $path
     * @param $response
     * @param string $url
     * @param string $request
     * @param string $msg
     */
    public static function saveProgramLog($path, $response, $url='', $request='', $msg = '')
    {
        file_put_contents($path, '发起时间：' . date('Y-m-d H:i:s') . $msg . ' 请求地址Url:' . $url . ' 请求数据：' . json_encode($request) . ' 返回数据：' . json_encode($response) . PHP_EOL);
    }



}